const express = require('express')
const uploader = require('express-fileupload')
const bodyParser = require('body-parser')
const { resolve, extname } = require('path')
const { readFileSync, writeFileSync, existsSync, appendFileSync } = require('fs')
const app = express()
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use(uploader())

app.use((req, res, next) => {
    res.header('access-control-allow-origin', '*');
    res.header('access-control-allow-methods', 'POST,PUT,GET');
    next()
})

app.use((req, res, next) => {
    console.log("🚀 ~ req:", new Date().getTime())
    next()
})
app.post('/video-uplaod', (req, res) => {
    const { name, fileName, size, type, uploadSize, event, chunkSize } = req.body
    // 是否上传结束
    if (uploadSize >= size) {
        res.send({
            code: 200,
            msg: '上传完成'
        })
        return;
    }
    const { file } = req.files
    const filePath = resolve(__dirname, `./video_temp/${fileName}.${type.split('/')[1]}`)
    // 有数据 已经上传过文件
    if (uploadSize != 0) {
        if (!existsSync(filePath)) {
            res.send({
                code: 401,
                msg: '没有该文件'
            })
            return;
        }
        appendFileSync(filePath, file.data)
        res.send({
            code: 200,
            msg: 'ok'
        })
        return;
    }
    // 写入一个文件
    writeFileSync(filePath, file.data)
    res.send({
        code: 200,
        msg: 'ok'
    })
})

app.listen(3000, () => {
    console.log('http://localhost:3000');

})